#include "pch.hpp"
#include "File.hpp"




void File::open(QFile& file, const QString& fname)
{
	QFileInfo info(fname);
	if(!info.exists())
		BOOSTEXT_THROW(exception("Unable to open file: it does not exist")
		<< boostext::file(qP(fname))
		);

	if(!info.isReadable())
		BOOSTEXT_THROW(exception("Unable to open file: it cannot be read")
		<< boostext::file(qP(fname))
		);

	file.setFileName(fname);
	if(!file.open(QIODevice::ReadOnly))
		BOOSTEXT_THROW(exception("Unable to open file")
		<< boostext::file(qP(fname))
		<< boostext::api_message(errorString(file.error()))
		);
}
///////////////////////////////////////////////////////////////////////////////////////////////////

QByteArray File::readAll(const QString& fname)
{
	QFile file;
	open(file, fname);

	int64 size = file.size();
	QByteArray data = file.readAll();
	if(data.size() != size)
		BOOSTEXT_THROW(exception("Could not read the entire file into memory")
		<< boostext::file(qP(fname))
		);

	return data;
}
///////////////////////////////////////////////////////////////////////////////////////////////////

const char* File::errorString(QFile::FileError error)
{
	switch(error)
	{
	case QFile::NoError: return "No error occurred";
	case QFile::ReadError: return "An error occurred when reading from the file";
	case QFile::WriteError: return "An error occurred when writing to the file";
	case QFile::FatalError: return "A fatal error occurred";
	case QFile::ResourceError: return "Unknown";
	case QFile::OpenError: return "The file could not be opened";
	case QFile::AbortError: return "The operation was aborted";
	case QFile::TimeOutError: return "A timeout occurred";
	case QFile::UnspecifiedError: return "An unspecified error occurred";
	case QFile::RemoveError: return "The file could not be removed";
	case QFile::RenameError: return "The file could not be renamed";
	case QFile::PositionError: return "The position in the file could not be changed";
	case QFile::ResizeError: return "The file could not be resized";
	case QFile::PermissionsError: return "The file could not be accessed";
	case QFile::CopyError: return "The file could not be copied";
	default: return "An Unknown error occured";
	}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
